package com.lottery.thrift;

import org.apache.thrift.TMultiplexedProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;

import com.lottery.api.IThriftEntryProcesser;
import com.lottery.api.impl.ThriftEntryProcesser;
import com.lottery.constant.GlobalConstants;

public class ThriftService {

  private static boolean isStart = false;

  @SuppressWarnings({ "rawtypes", "unchecked" })
  public static void start(Class<? extends ThriftEntryProcesser> clz, int port) {
    try {
      if (isStart) {
        System.out.println("Thrift server already started.");
        return;
      }
      TServerSocket serverTransport = new TServerSocket(port);
      IThriftEntryProcesser.Processor entryProcessor = new IThriftEntryProcesser.Processor(clz.newInstance());
      TMultiplexedProcessor processor = new TMultiplexedProcessor();
      processor.registerProcessor(GlobalConstants.THRIFT_SERVICE_NAME, entryProcessor);
      TThreadPoolServer.Args ttpsArgs = new TThreadPoolServer.Args(serverTransport);
      ttpsArgs.processor(processor);
      ttpsArgs.protocolFactory(new TBinaryProtocol.Factory());
      TServer server = new TThreadPoolServer(ttpsArgs);
      server.serve();
      System.out.println("Thrift server started on port " + port + " ...");
      isStart = true;
    } catch (TTransportException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}
